<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2012 Grzegorz Bańka <grzegorz.banka@gmail.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */


$LANG->includeLLFile('EXT:mt_elink/mod1/locallang.xml');
require_once(PATH_t3lib . 'class.t3lib_scbase.php');
$BE_USER->modAccess($MCONF,1);	// This checks permissions and exits if the users has no permission for entry.
	// DEFAULT initialization of a module [END]

require_once(PATH_t3lib . 'class.t3lib_scbase.php');
require_once(PATH_t3lib.'class.t3lib_tsparser.php');
require_once (PATH_t3lib.'class.t3lib_pagetree.php');

/**
 * Module 'MT Link SWL' for the 'mt_elink' extension.
 *
 * @author	Grzegorz Bańka <grzegorz.banka@gmail.com>
 * @package	TYPO3
 * @subpackage	tx_mtelink
 */
class  tx_mtelink_module1 extends t3lib_SCbase {
				var $pageinfo;

				/**
				 * Initializes the Module
				 * @return	void
				 */
				function init()	{
					global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;

					parent::init();

					/*
					if (t3lib_div::_GP('clear_all_cache'))	{
						$this->include_once[] = PATH_t3lib.'class.t3lib_tcemain.php';
					}
					*/
				}

				/**
				 * Adds items to the ->MOD_MENU array. Used for the function menu selector.
				 *
				 * @return	void
				 */
				function menuConfig()	{
					global $LANG;
					$this->MOD_MENU = Array (
						'function' => Array (
							'1' => $LANG->getLL('function1'),
							'2' => $LANG->getLL('function2')
						)
					);
					parent::menuConfig();
				}

				/**
				 * Main function of the module. Write the content to $this->content
				 * If you chose "web" as main module, you will need to consider the $this->id parameter which will contain the uid-number of the page clicked in the page tree
				 *
				 * @return	[type]		...
				 */
				function main()	{
					global $BE_USER,$LANG,$BACK_PATH,$TCA_DESCR,$TCA,$CLIENT,$TYPO3_CONF_VARS;

					// Access check!
					// The page will show only if there is a valid page and if this page may be viewed by the user
					$this->pageinfo = t3lib_BEfunc::readPageAccess($this->id,$this->perms_clause);
					$access = is_array($this->pageinfo) ? 1 : 0;
				
					if (($this->id && $access) || ($BE_USER->user['admin'] && !$this->id))	{

							// Draw the header.
						$this->doc = t3lib_div::makeInstance('mediumDoc');
						$this->doc->backPath = $BACK_PATH;
						$this->doc->form='<form action="" method="post" enctype="multipart/form-data">';

$this->doc->inDocStyles .= '
div.typo3-mediumDoc {
width:100%;
}
';

							// JavaScript
						$this->doc->JScode = '
							<script language="javascript" type="text/javascript">
								script_ended = 0;
								function jumpToUrl(URL)	{
									document.location = URL;
								}
							</script>
						';
						$this->doc->postCode='
							<script language="javascript" type="text/javascript">
								script_ended = 1;
								if (top.fsMod) top.fsMod.recentIds["web"] = 0;
							</script>
						';

						$headerSection = $this->doc->getHeader('pages', $this->pageinfo, $this->pageinfo['_thePath']) . '<br />'
							. $LANG->sL('LLL:EXT:lang/locallang_core.xml:labels.path') . ': ' . t3lib_div::fixed_lgd_cs($this->pageinfo['_thePath'], -50);

						$this->content.=$this->doc->startPage($LANG->getLL('title'));
						$this->content.=$this->doc->header($LANG->getLL('title'));
						$this->content.=$this->doc->spacer(5);
						$this->content.=$this->doc->section('',$this->doc->funcMenu($headerSection,t3lib_BEfunc::getFuncMenu($this->id,'SET[function]',$this->MOD_SETTINGS['function'],$this->MOD_MENU['function'])));
						$this->content.=$this->doc->divider(5);


						// Render content:
						$this->moduleContent();


						// ShortCut
						if ($BE_USER->mayMakeShortcut())	{
							$this->content.=$this->doc->spacer(20).$this->doc->section('',$this->doc->makeShortcutIcon('id',implode(',',array_keys($this->MOD_MENU)),$this->MCONF['name']));
						}

						$this->content.=$this->doc->spacer(10);
					} else {
							// If no access or if ID == zero

						$this->doc = t3lib_div::makeInstance('mediumDoc');
						$this->doc->backPath = $BACK_PATH;

						$this->content.=$this->doc->startPage($LANG->getLL('title'));
						$this->content.=$this->doc->header($LANG->getLL('title'));
						$this->content.=$this->doc->spacer(5);
						$this->content.=$this->doc->spacer(10);
					}
				
				}

				/**
				 * Prints out the module HTML
				 *
				 * @return	void
				 */
				function printContent()	{

					$this->content.=$this->doc->endPage();
					echo $this->content;
				}

				/**
				 * Generates the module content
				 *
				 * @return	void
				 */
				function moduleContent()	{
					switch((string)$this->MOD_SETTINGS['function'])	{
						case 1:
							if(isset($_POST['links']))
							{
								list($title_website,$rootsite,$storagefolder,$error)=$this->check_rootpage(intval($_GET['id']));
							
								$where = 'deleted=0 AND hidden=0 AND pid='.$rootsite;
								$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,constants,config','sys_template',$where,'','',1);
								while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
								{
									$constans = $this->parseTS($row['constants']);
								}
								if($constans['link_swl_pid']!=0 && $constans['link_swl_pid']!='')
								{
									$pid=intval($constans['link_swl_pid']);
									$links=explode("\n",$_POST['links']);
									for($i=0; $i<count($links); $i++)
									{
										if($links[$i]!='' && stristr($links[$i],';'))
										{
											list($link,$keyword)=explode(';',$links[$i]);
											if(stristr($keyword,'|'))
											{
												$keyword=explode('|',$keyword);
												for($z=0; $z<count($keyword); $z++)
												{
													if($keyword[$z]!='')
													{
														$add=array(
															'pid'			=>	$pid,
															'tstamp'		=>	time(),
															'crdate'		=>	time(),
															'title'			=>	$keyword[$z],
															'link'			=>	$link
														);
														$GLOBALS['TYPO3_DB']->exec_INSERTquery(
																'tx_mtelink_link',
																$add
														);
													}
												}
											}
											else
											{
												if($keyword!='')
												{
													$add=array(
														'pid'			=>	$pid,
														'tstamp'		=>	time(),
														'crdate'		=>	time(),
														'title'			=>	$keyword,
														'link'			=>	$link
													);
													$GLOBALS['TYPO3_DB']->exec_INSERTquery(
															'tx_mtelink_link',
															$add
													);
												}
											}
										}
									}
									$content='<h1>Dodano ('.count($links).') linków</h1>';
								}else
								{
									$content='<h1>Nie odnaleziono link_swl_pid</h1>';
								}
							}
							else
							{
								list($title_website,$rootsite,$storagefolder,$error)=$this->check_rootpage(intval($_GET['id']));
								if($error==1) 
								{
									$content='
									<h3>Wybierz stronę na której chcesz dodać treści</h3>
									<p>Użyj drzewa po lewej stronie i kliknij na nazwę strony z ikoną skrótu <b id="shortcut"></b></p>
									';
								}else
								{
									$content='
										<form action="" method="post">
											Dodajesz linki do <b>'.$title_website.'</b><br />
											<p>Dodaj linki, oddzielaj średnikiem keyword a kolejny link enterem w dół przykład:<br />
											http://typo3.org;serwis o TYPO3<br />
											http://google.pl;wyszukiwarka internetowa
											</p><br />
											
											<textarea name="links" cols="50" rows="10"></textarea>
											<br />
											<input name="" type="submit" value="Dodaj linki do strony" />
																						
											<p>Dodając nowe linki nie nadpisujesz istniejących</p>
										</form>
									';
								}
							}
							$this->content.=$this->doc->section('Add links:',$content,0,1);
						break;
						case 2:
						
							list($title_website,$rootsite,$storagefolder,$error)=$this->check_rootpage(intval($_GET['id']));
							if(!isset($_POST['clear_links']))
							{
								if($error==1) 
								{
									$content='
									<h3>Wybierz stronę na której chcesz dodać treści</h3>
									<p>Użyj drzewa po lewej stronie i kliknij na nazwę strony z ikoną skrótu <b id="shortcut"></b></p>
									';
								}else
								{
									$content='
									<div align=center><strong>Usuwanie wszystkich linków z magazynu strony</strong><br />
									<b>'.$title_website.'</b><br />
									<input name="clear_links" type="submit" value="Tak chcę wyczyścić linki na tej stronie" onClick="return confirm(\'Jesteś tego pewien? utracisz wszystkie linki na stronie '.$title_website.'\')" />
									</div>';
								}	
							}
							else
							{
								list($title_website,$rootsite,$storagefolder,$error)=$this->check_rootpage(intval($_GET['id']));
							
								$where = 'deleted=0 AND hidden=0 AND pid='.$rootsite;
								$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,constants,config','sys_template',$where,'','',1);
								while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
								{
									$constans = $this->parseTS($row['constants']);
								}
								if($constans['link_swl_pid']!=0 && $constans['link_swl_pid']!='')
								{
									$query = $GLOBALS['TYPO3_DB']->DELETEquery('tx_mtelink_link', 'pid='.intval($constans['link_swl_pid']));		
									$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
									$content='<h1>Usunięto linki ze strony '.$title_website.'</h1>';
								}
							}					

							$this->content.=$this->doc->section('Uwaga utrata linków jest nieodwracalna:',$content,0,1);
						break;
					}
				}
			function parseTS($tsString)
			{
				$TSparserObject = t3lib_div::makeInstance('t3lib_tsparser');
				$TSparserObject->parse($tsString);
				return $TSparserObject->setup;
			}
				function check_rootpage($uid)
				{
					$error=1;
				
					$where = 'deleted=0 AND hidden=0 AND is_siteroot=0 AND uid='.$uid;
					$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','pages',$where);
					while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
					{
						$error=0;
						$title_website=$row['title'];
					}	
					if($error==0)
					{
						$error=1;
						$where = 'deleted=0 AND hidden=0 AND is_siteroot=1 AND pid='.$uid;
						$res =  $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,storage_pid','pages',$where);
						while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))
						{
							$storagefolder=$row['storage_pid'];
							$rootsite=$row['uid'];							
							if($storage_pid!=0 || $rootsite!=0) $error=0;
							else $error=1;
						}	
					}
					return array($title_website,$rootsite,$storagefolder,$error);			
				}
				
		}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mt_elink/mod1/index.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/mt_elink/mod1/index.php']);
}




// Make instance:
$SOBE = t3lib_div::makeInstance('tx_mtelink_module1');
$SOBE->init();

// Include files?
foreach($SOBE->include_once as $INC_FILE)	include_once($INC_FILE);

$SOBE->main();
$SOBE->printContent();

?>